package com.huanglejing.shanggou.helper

import android.support.v7.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.huanglejing.shanggou.utils.C
import com.huanglejing.shanggou.view.EmptyLayout

/**
 * Created by Administrator on 2017/1/9 0009.
 * 通用分页加载的RecyclerView状态处理器
 */
open class RecyclerViewStateHelper<T>(val recyclerView: RecyclerView, val quickAdapter: BaseQuickAdapter<T, BaseViewHolder>) {

    val emptyLayout by lazy { quickAdapter.emptyView?.findViewWithTag<EmptyLayout>(EmptyLayout::class.java.name) as? EmptyLayout }

    init {
        if (recyclerView.adapter != quickAdapter) {
            quickAdapter.bindToRecyclerView(recyclerView)
        }
    }

    open fun resetList(pageSize: Int = C.Page.PAGE_ROW) {
        quickAdapter.data.clear()
        quickAdapter.removeAllFooterView()
        quickAdapter.removeAllHeaderView()
        quickAdapter.notifyDataSetChanged()
    }

    open fun loadComplete(end: Boolean = false) {
        quickAdapter.setHeaderAndEmpty(quickAdapter.headerLayoutCount > 0)
        recyclerView.post {
            quickAdapter.loadMoreComplete()
            if (end) {
                quickAdapter.loadMoreEnd()
                if (quickAdapter.data.size <= 0) {
                    emptyLayout?.setErrorType(EmptyLayout.NODATA)
                }
            }
//            KLog.d("$quickAdapter .data = ${quickAdapter.data}")
//            if (quickAdapter.data.size != 0) {
//                //加载更多完成或者第一页完成
//                val emptyLayout = EmptyLayout.getEmptyLayout(EmptyLayout.COMPLETE, recyclerView)
//                quickAdapter.addFooterView(emptyLayout)
//            } else {
//                emptyLayout?.setErrorType(EmptyLayout.NODATA)
//            }
        }
    }

    open fun showError(e: Throwable?) {
        //网络错误，或者加载错误
        if (quickAdapter.data.size == 0) {
            //网络错误或出现异常，因此没有数据

            emptyLayout?.setErrorType(EmptyLayout.NETWORK_ERROR)
        } else {
            recyclerView.post {
                quickAdapter.removeAllFooterView()
                quickAdapter.loadMoreFail()
            }
        }
    }

}